package com.qwt.part_time_api.handler;

import com.qwt.part_time_api.error.ErrorCode;
import com.qwt.part_time_api.utils.JsonAuthentication;
import com.qwt.part_time_api.utils.JwtUtil;
import com.qwt.part_time_api.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author Tzeao
 * 登出成功处理器
 */
@Component
@Slf4j
public class LocalLogoutSuccessHandler extends JsonAuthentication implements LogoutSuccessHandler {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        //如果为null 就代表没登陆
        if (Objects.isNull(authentication)) {
            log.info("还没登录或已经退出");
            this.writeJson(request, response, Result.fail(ErrorCode.USER_LOGOUT_FAIL.getErrCode(), ErrorCode.USER_LOGOUT_FAIL.getErrMsg()));
            return;
        }

        String name = authentication.getName();
        // 删除redis的token
        redisTemplate.delete("QWT-TOKEN_" + name);
        //删除登录状态
        redisTemplate.delete(name + "_QWT-STATE");
        //清除响应头值
        //设置响应头
        response.setHeader(JwtUtil.getHeader(), null);

        Result success = Result.success(ErrorCode.USER_LOGOUT_SUCCESS.getErrMsg());
        log.info("登出成功");
        //继承封装的输出JSON格式类，并调用父类方法即可
        this.writeJson(request, response, success);
    }
}